package com.luguangxing.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import androidx.annotation.Nullable;
import com.xuexiang.xui.utils.XToastUtils;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.*;

/**
 * @author: 小白一号
 * @date: 2022/11/28
 * @desc:
 */
public class MQTTService extends Service implements MqttCallback {
    private static final String HOST = "tcp://2.tcp.cpolar.top:11595";
    private static final String USERNAME = "admin";
    private static final String PSD = "whiteone@lu";
    private static MqttAndroidClient androidClient;
    private MqttConnectOptions connectOptions;
    private static final String TOPIC = "WaterOX/android";
    private static final String CLIENTID = "123456789";
    private static final int QOS = 0;    //传输质量

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        androidClient = new MqttAndroidClient(this, HOST, CLIENTID);
        androidClient.setCallback(this);
        connectOptions = new MqttConnectOptions();
        connectOptions.setCleanSession(true);
        connectOptions.setConnectionTimeout(10);
        connectOptions.setKeepAliveInterval(20);
        connectOptions.setUserName(USERNAME);
        connectOptions.setPassword(PSD.toCharArray());
        //设置最后的遗嘱
        boolean doConnect = true;
        String message = "{\"terminal_uid\":\"" + CLIENTID + "\"}";
        if (!message.equals("")) {
            connectOptions.setWill(TOPIC, message.getBytes(), QOS, true);
        }
        if (doConnect) {
            doClientConnection();
        }
    }

    //发送消息
    public void sendMessage(String message) {
        if (androidClient != null && androidClient.isConnected()) {
            try {
                androidClient.publish(TOPIC, message.getBytes(), QOS, true);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        } else {
            doClientConnection();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new CustomBinder();
    }

    @Override
    public void onDestroy() {
        if (androidClient != null) {
            try {
                androidClient.disconnect();
                androidClient.unregisterResources();
                androidClient.close();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }

    private void doClientConnection() {
        if (!androidClient.isConnected()) {
            try {
                androidClient.connect(connectOptions, null, iMqttActionListener);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            //连接成功
            XToastUtils.info("MQTT" + "---->connection success");
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            //连接失败
            XToastUtils.info("MQTT" + "---->connection failure" + exception.toString());
            doClientConnection();
        }
    };

    public class CustomBinder extends Binder {
        public MQTTService getService() {
            return MQTTService.this;
        }
    }

    /**
     * 连接并监听消息
     *
     * @param cause
     */
    @Override
    public void connectionLost(Throwable cause) {
        XToastUtils.info("MQTT" + "---->connectionLost:" + cause.toString());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String getMessage = new String(message.getPayload());
        XToastUtils.info("MQTT" + "---->Message:" + getMessage);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}

